package com.zjx.reggie.controller;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.zjx.reggie.common.R;
import com.zjx.reggie.util.OSSProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;

import java.io.InputStream;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/common")
public class CommonController {


    @PostMapping("/upload")
    public String upload(MultipartFile file) {
        String name = file.getOriginalFilename();
        log.info(name);
        String suffix = name.substring(name.indexOf("."));
        String prefix = UUID.randomUUID().toString();
        String filename = prefix + suffix;

        OSS ossClient = new OSSClientBuilder().build(OSSProperties.ENDPOINT, OSSProperties.KEY_ID, OSSProperties.KEY_SECRET);
        if (!ossClient.doesBucketExist(OSSProperties.BUCKET_NAME)){
            ossClient.createBucket(OSSProperties.BUCKET_NAME);
            ossClient.setBucketAcl(OSSProperties.BUCKET_NAME, CannedAccessControlList.PublicRead);
        }
        try {
            // 创建PutObject请求。
            ossClient.putObject(OSSProperties.BUCKET_NAME, filename, file.getInputStream());
        } catch (Exception ce) {
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        return "https://"+ OSSProperties.BUCKET_NAME+"."+OSSProperties.ENDPOINT+"/"+filename;
    }


}
